package cn.yunlang.zhangZhongFei.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.yunlang.zhangZhongFei.entity.User;
import cn.yunlang.zhangZhongFei.mapper.UserMapper;
import cn.yunlang.zhangZhongFei.service.UserService;
import cn.yunlang.zhangZhongFei.util.CheckEmptyUtil;
import cn.yunlang.zhangZhongFei.util.JwtUtil;
import cn.yunlang.zhangZhongFei.util.RedisUtil;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

  @Resource private UserMapper userMapper;
  @Resource private RedisUtil redisUtil;

  private static final String USER_KEY = "USER";

  @Override
  public User queryUserDetailsByUserId(Long userId) {
    String userString = redisUtil.hget(USER_KEY, userId.toString());
    // if (CheckEmptyUtil.isEmpty(userString) || userString.equals("null")) {
    if (userId != null) {
      User user = userMapper.selectById(userId);
      redisUtil.hset(USER_KEY, userId.toString(), JSON.toJSONString(userString), 300);
      return user;
    }
    return JSON.parseObject(userString, User.class);
  }

  @Override
  public void updateUserDetailsByUserId(User user) {
    String userId = new JwtUtil().getUserId();
    if (!CheckEmptyUtil.isEmpty(userId)) {
      userMapper.updateById(user);
      redisUtil.hset(
          USER_KEY,
          user.getId().toString(),
          JSON.toJSONString(userMapper.selectById(user.getId())),
          300);
    }
  }
}
